﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GRWL.BZSC.UI.BaseDataSvc;
using System.Configuration;
using BaseClass;
using System.Windows;
using GRWL.BZSC.UI.CustomCtrl;
using UserCtrl;


namespace GRWL.BZSC.UI
{
    public partial class TraderFrm : BaseFrm
    {
        //调用：
        //            
        //供应商分类        
        //OptionFrm frmSupplier = new OptionFrm();        
        //frmSupplier.CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.供应商分类;        
        //frmSupplier.Show();
        //    
        //客户分类        
        //OptionFrm frmClient = new OptionFrm();        
        //frmClient.CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.客户分类;        
        //frmClient.Show();
        //
        //供应商
        //TraderFrm frmSupplier = new TraderFrm();
        //frmSupplier.SetTraderAsSupplier();
        //frmSupplier.Show();
        //
        //客户
        //TraderFrm frmClient = new TraderFrm();
        //frmClient.SetTraderAsClient();
        //frmClient.Show();

        /// <summary>
        /// 选择器窗体返回项
        /// </summary>
        public SelectItem SelectorItem { get; set; }

        /// <summary>
        /// 记住当前设置的编码规则
        /// </summary>
        //public CodeRuleFrm.CodeRule codeRule { get; set; }

        //private GRWL.BZSC.Common.EnumCommon.OptionType _CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.供应商分类;
        public GRWL.BZSC.Common.EnumCommon.OptionType CurrentType { get; set; }

        // 默认进入供应商记录编辑, 客户记录编辑调用设定为 false
        private bool isSupplierType;
        public bool IsSupplierType
        {
            get { return this.isSupplierType; }
            set { this.isSupplierType = value; }
        }
        // 传递到后台的查找参数
        private bool isSupplier;
        public bool IsSupplier
        {
            get { return isSupplier; }
            set { isSupplier = value; }
        }
        private bool isClient;
        public bool IsClient
        {
            get { return isClient; }
            set { isClient = value; }
        }
        private bool SearchMode = false;

        private string isSupplierString = "供应商分类";
        private string isClientString = "客户分类";
        private string StrType = "仓库分类";

        //private int? type;
        private string SearchCode;
        private string SearchName;
        private string SearchLinkMan;
        private TB_Options[] options;

        /// <summary>
        /// 指定窗体进入供应商浏览、编辑状态
        /// </summary>
        public void SetTraderAsSupplier()
        {
            isSupplierType = true;
            isSupplier = true;
        }

        /// <summary>
        /// 指定窗体进入客户浏览、编辑状态
        /// </summary>
        public void SetTraderAsClient()
        {
            isSupplierType = false;
            isClient = true;
        }

        /// <summary>
        /// 指定窗体进入供应商浏览、选择状态
        /// </summary>
        public void SearchSupplierMode()
        {
            SetTraderAsSupplier();
            btnSelect.Visible = true;
            SearchMode = true;
        }

        /// <summary>
        /// 指定窗体进入客户浏览、选择状态
        /// </summary>
        public void SearchClientMode()
        {
            SetTraderAsClient();
            btnSelect.Visible = true;
            SearchMode = true;
        }

        public TraderFrm()
        {
            InitializeComponent();

            this.BaseDataProxy = new BaseDataClient();
            this.BaseDataProxy.Open();

            this.codeRule = new CodeRuleFrm.CodeRule();

        }

        #region 处理外部委托
        /// <summary>
        /// 接收处理UpdateTreeViewDlgt
        /// </summary>
        /// <param name="o"></param>
        /// <param name="add"></param>
        private void UpdateTreeView(object o, EventArgs arg)
        {
            CommonEventArg<TB_Options> argObj = (CommonEventArg<TB_Options>)arg;

            //检查是否当前窗体编辑结点，确保只更新当前窗体的内容，其他声明同样事件的窗体不更新。
            if (this.CurrentType.ToString() != argObj.t.type)
                return;

            if (this.uTreeView1.SelectedNode != null)
            {
                string showText = argObj.t.code + "[" + argObj.t.name + "]";
                if (argObj.OpType == Common.OperateType.Add)
                {
                    TreeNode node = new TreeNode();
                    node.Name = argObj.t.id.ToString();
                    node.Text = showText;
                    node.Tag = argObj.t.code;
                    this.uTreeView1.SelectedNode.Nodes.Add(node);
                }
                else { this.uTreeView1.SelectedNode.Text = showText; }
            }
        }

        private void UpdateDataGridView(object o, EventArgs arg)
        {
            if (arg != null)
            {
                CommonEventArg<TB_Trader> tdr = (CommonEventArg<TB_Trader>)arg;
                TB_Trader d = tdr.t;
                //id, name, linkman, tel, address, fax, taxRate, type, isClient, isSupplier                
                object[] ary = { d.id, d.code, d.name, d.linkman, d.tel, d.address, d.fax, d.taxRate, d.type, d.isClient, d.isSupplier };
                if (tdr.OpType == Common.OperateType.Add)
                {
                    this.uDataGridView.Rows.Add(ary);
                }
                else
                {
                    //this.uDataGridView.SelectedRows[0].SetValues(ary);
                    this.uDataGridView.CurrentRow.SetValues(ary);
                }
            }
        }
        #endregion

        private void traderFrm_Load(object sender, EventArgs e)
        {
            try
            {
                options = null;
                if (isSupplierType == true)
                {
                    options = this.BaseDataProxy.GetOptionTree(GRWL.BZSC.Common.EnumCommon.OptionType.供应商分类.ToString());
                    this.CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.供应商分类;
                    this.Text = "供应商";
                    StrType = isSupplierString;
                }
                else
                {
                    options = this.BaseDataProxy.GetOptionTree(GRWL.BZSC.Common.EnumCommon.OptionType.客户分类.ToString());
                    this.CurrentType = GRWL.BZSC.Common.EnumCommon.OptionType.客户分类;
                    this.Text = "客户";
                    StrType = isClientString;
                }

                //解除数据源绑定，在过程bindGV中用代码生成uDataGridView显示的记录。
                uDataGridView.DataSource = null;
                bindTree(this.uTreeView1);

                if (isSupplierType)
                {
                    //GRWL.BZSC.Common.EventCommon.SupplierUdTVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateTreeViewDlgt(UpdateTreeView);
                    GRWL.BZSC.Common.EventCommon.SupplierUdDGVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateDataGridViewDlgt(UpdateDataGridView);
                }
                else
                {
                    //GRWL.BZSC.Common.EventCommon.ClientUdTVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateTreeViewDlgt(UpdateTreeView);
                    GRWL.BZSC.Common.EventCommon.ClientUdDGVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateDataGridViewDlgt(UpdateDataGridView);
                }
                GRWL.BZSC.Common.EventCommon.OptionUdTVEvnt += new GRWL.BZSC.Common.EventCommon.UpdateTreeViewDlgt(UpdateTreeView);
                uDataGridView.CellDoubleClick += new DataGridViewCellEventHandler(uDataGridView_CellDoubleClick);
                uDataGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(uDataGridView_CellFormatting);
            }
            catch (InvalidCastException eMsg)
            {
                MessageBox.Show(eMsg.Message.ToString());
            }
        }

        void uDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            Common.CellFormatColor(sender, e, Common.BillOperateType.View);
        }

        void uDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0)
                return;

            if (SearchMode)
            {
                ReturnSelectTrader();
            }
            else
            {
                //clType
                if (uDataGridView.Columns[e.ColumnIndex].Name == "clType")
                {
                    OptionFrm frm = new OptionFrm();
                    if (isSupplierType)
                        frm.OType = GRWL.BZSC.Common.EnumCommon.OptionType.供应商分类;
                    else
                        frm.OType = GRWL.BZSC.Common.EnumCommon.OptionType.客户分类;
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        string message = "是否替换剩下的同一分类？";
                        string caption = "确认";
                        MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                        DialogResult result = MessageBox.Show(message, caption, buttons);
                        if (result == DialogResult.Yes)
                        {
                            string sId = uDataGridView.CurrentRow.Cells["clType"].Value.ToString();
                            DataGridViewRow TheRow;
                            for (int iIndex = uDataGridView.CurrentRow.Index; iIndex < uDataGridView.Rows.Count; iIndex++)
                            {
                                TheRow = uDataGridView.Rows[iIndex];
                                if (TheRow.Cells["clType"].Value.ToString() != sId)
                                    break;
                                ReplaceCategory(TheRow, frm.SelectorItem.Value, frm.SelectorItem.Key, frm.SelectorItem.Name);
                            }
                        }
                        else
                        {
                            ReplaceCategory(uDataGridView.CurrentRow, frm.SelectorItem.Value, frm.SelectorItem.Key, frm.SelectorItem.Name);
                        }
                    }
                    return;
                }
                else
                    //clCode
                    //if ((uDataGridView.Columns[e.ColumnIndex].Name == "clCode") | (uDataGridView.Columns[e.ColumnIndex].Name == "clName"))
                    EditSelectTrader();
            }
        }

        private void ReplaceCategory(DataGridViewRow TheRow, string TypeId, string TypeCode, string TypeName)
        {
            TheRow.Cells["clType"].Value = TypeId;
            TB_Trader Trader = new TB_Trader();
            Trader.id = (int)TheRow.Cells["clId"].Value;
            Trader.code = (string)TheRow.Cells["clCode"].Value;
            Trader.name = (string)TheRow.Cells["clName"].Value;
            Trader.linkman = (string)TheRow.Cells["clLinkMan"].Value;
            Trader.tel = (string)TheRow.Cells["clTel"].Value;
            Trader.fax = (string)TheRow.Cells["clFax"].Value;
            Trader.address = (string)TheRow.Cells["clAddress"].Value;
            Trader.isClient = (bool)TheRow.Cells["clIisClient"].Value;
            Trader.isSupplier = (bool)TheRow.Cells["clIsSupplier"].Value;
            Trader.taxRate = (decimal)TheRow.Cells["clTaxRate"].Value;
            Trader.type = Common.StringToInt(TypeId);
            BaseDataProxy.UpdateTrader(Trader);
        }

        #region 树建立
        private void bindTree(UserCtrl.UTreeView tv)
        {
            Common.BindOptionTree(tv, options, this.CurrentType.ToString());
            bindGV(null);
        }
        #endregion 树建立

        #region 树分类编辑
        private void addType_Click(object sender, EventArgs e)
        {
            Control ctrl = this.contextMenuStrip1.SourceControl;
            if (ctrl != null)
            {
                UserCtrl.UTreeView tv = (UserCtrl.UTreeView)ctrl;
                EditOptionFrm frm = new EditOptionFrm();
                frm.EditMode = false;
                int parentId = tv.SelectedNode.Name == string.Empty ? 0 : Convert.ToInt32(tv.SelectedNode.Name);
                frm.ParentId = parentId;
                frm.OType = this.CurrentType;
                frm.ShowDialog(this);
            }
        }

        private void updateType_Click(object sender, EventArgs e)
        {
            Control ctrl = this.contextMenuStrip1.SourceControl;
            if (ctrl != null)
            {
                UserCtrl.UTreeView tv = (UserCtrl.UTreeView)ctrl;
                if (!string.IsNullOrEmpty(tv.SelectedNode.Name))
                {
                    EditOptionFrm frm = new EditOptionFrm();
                    frm.EditMode = true;
                    frm.Id = Convert.ToInt32(tv.SelectedNode.Name);
                    frm.ShowDialog(this);
                }
            }
        }

        private void deleteType_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认删除该项吗？", "删除提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if (!string.IsNullOrEmpty(this.uTreeView1.SelectedNode.Name))
                {
                    this.BaseDataProxy.DeleteOption(Convert.ToInt32(this.uTreeView1.SelectedNode.Name));
                    this.uTreeView1.Nodes.Remove(this.uTreeView1.SelectedNode);
                }
            }
        }
        #endregion 树分类编辑

        #region 记录编辑
        private int currentType()
        {
            int checkType = 0;
            if (uTreeView1.Nodes.Count == 0)
                checkType = 0;
            else
                if (this.uTreeView1.SelectedNode != null && !string.IsNullOrEmpty(this.uTreeView1.SelectedNode.Name))
                    checkType = Convert.ToInt32(this.uTreeView1.SelectedNode.Name);

            return checkType;
        }

        //private string GetFieldName(string SearchKey)
        //{
        //    //取绑定到id字段的列名字
        //    string sFieldName = "";
        //    foreach (DataGridViewColumn cSearch in uDataGridView.Columns)
        //    {
        //        if (cSearch.DataPropertyName == SearchKey)
        //        {
        //            sFieldName = cSearch.Name;
        //        }
        //    }
        //    return sFieldName;
        //}

        private void btnAppend_Click(object sender, EventArgs e)
        {
            EditSupplierFrm EditSupplierFrm = new EditSupplierFrm();
            EditSupplierFrm.IsSupplierRec = isSupplierType;
            // 输入新纪录时,需要指定分类
            EditSupplierFrm.Type = currentType();
            EditSupplierFrm.EditMode = false;
            EditSupplierFrm.ShowDialog(this);
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            EditSelectTrader();
        }

        private void EditSelectTrader()
        {
            if (uDataGridView.CurrentRow == null)
                return;
            EditSupplierFrm EditSupplierFrm = new EditSupplierFrm();
            EditSupplierFrm.IsSupplierRec = isSupplierType;
            EditSupplierFrm.EditMode = true;
            EditSupplierFrm.Id = Convert.ToInt32(uDataGridView.CurrentRow.Cells["clId"].Value); //GetFieldName("id")
            EditSupplierFrm.ShowDialog(this);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (uDataGridView.CurrentRow == null)
                return;
            // Configure message box
            string message = "是否删除记录？";
            string caption = "确认";
            MessageBoxButtons buttons = MessageBoxButtons.YesNo;
            // Show message box
            DialogResult result = MessageBox.Show(message, caption, buttons);
            if (result == DialogResult.Yes)
            {
                try
                {
                    if (uDataGridView.SelectedRows.Count == 0)
                        uDataGridView.CurrentRow.Selected = true;
                    //根据id删除所有选择的纪录
                    foreach (DataGridViewRow rSel in uDataGridView.SelectedRows)
                    {
                        //"idDataGridViewTextBoxColumn"
                        int id = Convert.ToInt32(rSel.Cells["clId"].Value); //GetFieldName("id")
                        if (!this.BaseDataProxy.DeleteTrader(id))
                        {
                            MessageBox.Show("无法删除记录.");
                            return;
                        }
                        uDataGridView.Rows.Remove(rSel);
                    }
                    MessageBox.Show("已成功删除记录.");
                }
                catch (InvalidCastException eMsg)
                {
                    MessageBox.Show(eMsg.Message.ToString());
                }
            }
        }
        #endregion 记录编辑

        #region 记录刷新
        private void uTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            bindGV(null);
        }

        private void bindGV(int? type)
        {
            type = null;
            if (this.uTreeView1.SelectedNode != null && !string.IsNullOrEmpty(uTreeView1.SelectedNode.Name))
                type = Convert.ToInt32(this.uTreeView1.SelectedNode.Name);

            uDataGridView.SuspendLayout();
            uDataGridView.Rows.Clear();
            TB_Trader[] objAry = BaseDataProxy.FindTraders(type, isSupplier, isClient, this.txtCode.Text.Trim(), this.txtName.Text.Trim(), this.txtLinkMan.Text.Trim());
            if (objAry != null)
            {
                foreach (TB_Trader d in objAry)
                {
                    uDataGridView.Rows.Add(d.id, d.code, d.name, d.linkman, d.tel, d.address, d.fax, d.taxRate, d.type, d.isClient, d.isSupplier);
                }
            }
            uDataGridView.ResumeLayout();
        }
        #endregion 记录刷新

        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchCode = null;
            SearchName = null;
            SearchLinkMan = null;
            UDataGridView TheView = uDataGridView;

            if (!string.IsNullOrEmpty(this.txtCode.Text.Trim()))
            {
                SearchCode = this.txtCode.Text.ToLower().Trim();
                ViewSearch(uDataGridView, "clCode", SearchCode);
            }
            else
                if (!string.IsNullOrEmpty(this.txtName.Text.Trim()))
                {
                    SearchName = this.txtName.Text.ToLower().Trim();
                    ViewSearch(uDataGridView, "clName", SearchName);
                }
                else
                    if (!string.IsNullOrEmpty(this.txtLinkMan.Text.Trim()))
                    {
                        SearchLinkMan = this.txtLinkMan.Text.ToLower().Trim();
                        ViewSearch(uDataGridView, "clLinkMan", SearchLinkMan);
                    }
        }

        private bool ViewSearch(UDataGridView TheView, string SearchCellName, string SearchKey)
        {
            if (string.IsNullOrEmpty(SearchCellName))
                return false;
            if (string.IsNullOrEmpty(SearchKey))
                return false;

            SearchCellName = SearchCellName.ToLower().Trim();
            SearchKey = SearchKey.ToLower().Trim();

            if (SearchKey != null)
                foreach (DataGridViewRow TheRow in uDataGridView.Rows)
                {
                    if (TheRow.Index <= TheView.CurrentRow.Index)
                        continue;
                    if (TheRow.Cells[SearchCellName].Value.ToString().ToLower().IndexOf(SearchKey) >= 0)
                    {
                        TheView.ClearSelection();
                        TheRow.Selected = true;
                        TheView.CurrentCell = TheRow.Cells[SearchCellName];
                        break;
                    }
                }

            return true;
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (!(uDataGridView.CurrentRow == null))
            {
                ReturnSelectTrader();
            }
        }

        private void ReturnSelectTrader()
        {
            if (!SearchMode)
                return;

            SelectItem item = new SelectItem();
            DataGridViewRow rSel = uDataGridView.CurrentRow;
            if (rSel.Cells["clCode"].Value != null)
                item.Key = rSel.Cells["clCode"].Value.ToString();
            if (rSel.Cells["clName"].Value != null)
                item.Name = rSel.Cells["clName"].Value.ToString();
            if (rSel.Cells["clId"].Value != null)
                item.Value = rSel.Cells["clId"].Value.ToString();
            this.SelectorItem = item;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

    }
}
